#!/usr/bin/env python

from parser import Parser
import sys
import PdfBackend

class PdfMaker(object):
	"""Creates a pdf file from a given document structure in HTML like syntax"""
	def __init__(self, file=None, verbose=0):
		"""Creates the object setting as default output file 'file' and choosing between verbose report or not"""
		self._file = file
		self._verbose = verbose
	
	def __replace_dict(self, text, dict):
		while ( text.find( "%(" ) != -1 ):
			text = text % dict
		return text
		
	def __read_dict(self, file):
		dict = {}
		for i in open(file, 'r').readlines():
			i = i.strip()
			key,value = i.split(':')
			print '['+key+'] = "'+value+'"'
			dict[key] = value
		return dict
		
	def create(self, destination_file, source_file=None, dict={}):
		"""Creates a pdf document from the given source_file and saves it to destination_file.
		Replaces every text of the form %(name) with dict[name] value"""
		file = self._file or source_file
		try:
			lines = open(file, 'r').read()
		except Exception, e:
			sys.stderr.write("Error opening file "+file+" to parse document template\n")
			print e
		self.create_from_str(destination_file, lines, dict)
				
	def create_from_str ( self, destination_file, lines, dict = None ):
		"""Creates a pdf document from the given string (lines) and saves it to destination_file.
		Replaces every text of the form %(name) with dict[name] value"""
		if dict:
			print "REPLACING TEXT..."
			if type(dict).__name__ == 'str':
				dict = self.__read_dict(dict)
			lines = self.__replace_dict(lines, dict)
 		parser = Parser(lines, destination_file, PdfBackend, self._verbose)
		parser.run()
		parser.save_document()

		
if __name__ == "__main__":
#	try:
		if len ( sys.argv ) < 4:
			print "maker  (input template) (output file name) (dictionary) [verbose]"
			sys.exit ( 1 )


		if len ( sys.argv ) == 5: verbose = 1
		else: verbose = 0

		maker = PdfMaker ( verbose = verbose )
		maker.create ( sys.argv [ 2 ], sys.argv [ 1 ], sys.argv [ 3 ] )
#	except:
#		print "QUITTING ON ERROR..."
